#include "terminal.h"
#include <ctype.h>
TaskHandle_t TerminalHandle;
#define TERMINAL_STACK_SIZE		2048
#define TERMINAL_PRIORITY		14
#define TERMINAL_LINE_SIZE		128
#define TERMINAL_LINE_HEAD		"\nSTM32F429~$"

struct terminalStruct {
	uint8_t ch;
	char line[TERMINAL_LINE_SIZE];
	uint8_t curpos;
} terminal;

static void cmd_process(void) {
	uint8_t i;
	for(i=0;i<strlen(terminal.line);i++) {
		if (islower(terminal.line[i])) terminal.line[i]=toupper(terminal.line[i]);
	}
	printf("\nlength = %d -> %s", strlen(terminal.line), terminal.line);
}

//static void auto_complete(void) {
//	
//}

static void terminal_entry(void * pvParameters) {
	pvParameters = pvParameters;
	terminal.curpos = 0;
	memset(terminal.line, 0, TERMINAL_LINE_SIZE);
	printf("%s", TERMINAL_LINE_HEAD);
	while(1) {
		terminal.ch = getchar();

		/* received null or error */
        if (terminal.ch == '\0' || terminal.ch == 0xFF) continue;
//		else if(terminal.ch == 0x09)
//        {
//            int i;
//            /* move the cursor to the beginning of line */
//            for (i = 0; i < terminal.curpos; i++)
//                printf("\b");
//            /* auto complete */
//            auto_complete();
//            /* re-calculate position */
//            terminal.curpos = strlen(terminal.line);
//        }
		else if(terminal.ch == 0x08) {
			if(terminal.curpos) {
				printf("\b \b");
				terminal.curpos --;
				terminal.line[terminal.curpos] = NULL;
			}
		}
		else if (terminal.ch == 0x0D) {
			cmd_process();
			terminal.curpos = 0;
			memset(terminal.line, 0, TERMINAL_LINE_SIZE);
			printf("%s", TERMINAL_LINE_HEAD);
		}
		else if(terminal.ch >= 32 && terminal.ch <= 126) {
			if(terminal.curpos < (TERMINAL_LINE_SIZE-1)) {
				printf("%c", terminal.ch);
				terminal.line[terminal.curpos] = terminal.ch;
				terminal.curpos ++;
			}
		}
	}
}

void Terminal_Init(void) {
	if(xTaskCreate(terminal_entry, "terminal", TERMINAL_STACK_SIZE, NULL, TERMINAL_PRIORITY, &TerminalHandle) != pdPASS) {
		printf("terminal creat fail.\n");
	}
	else {
		printf("terminal created.\n");
		
	}
}
